import { createI18n } from 'vue-i18n'
import { __getLocal } from '@/utils/tools.js'
import useAppStore from '@/stores/app'
import { storeToRefs } from 'pinia'
import { __setLocal } from '@/utils/tools.js'

import enLocale from './en'
import zhLocale from './zh'
const messages = {
  en: {
    ...enLocale
  },
  zh: {
    ...zhLocale
  }
}

export function setLocale(lang) {
  // 获取当前语言
  const appStore = useAppStore()
  const { language } = storeToRefs(appStore)

  i18n.global.locale.value = lang // 修改 i18n
  language.value = lang // 修改 pinia
  __setLocal('LANGUAGE', lang) // 修改缓存
}

export function getLanguage() {
  const chooseLanguage = __getLocal('LANGUAGE', '')
  console.log('chooseLanguage', chooseLanguage)
  if (chooseLanguage) return chooseLanguage

  // if has not choose language
  const language = (navigator.language || navigator.browserLanguage).toLowerCase()
  const locales = Object.keys(messages)
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale
    }
  }
  return 'zh'
}
const i18n = createI18n({
  legacy: false,
  locale: getLanguage(),
  messages
})
export default i18n
